<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\common\model;

use buwang\base\BaseModel;
use buwang\util\Caches;

class Sms extends BaseModel
{
    /**
     * 验证码有效时间
     * @var int
     */
    private static $expire_time = 300;

    public static function send($mobile, $code, $event)
    {
        $ip = get_real_ip();
        self::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip]);

        $param = [
            'mobile' => $mobile,
            'code' => $code,
        ];
        //NOTE 调用阿里云短信
//        hook('alismsSendHook', $param);
        //NOTE 调用阿里云云市场短信
        if(env('app_debug') != '1'){
            $cloudSms = new \buwang\service\cloud\Sms();
            $res = $cloudSms->run($param);
            if (!$res) return self::setError(\buwang\service\cloud\Sms::getError());
        }

        Caches::set("{$mobile}-{$event}", $code, self::$expire_time);

        return true;
    }

    public static function check($mobile, $code, $event, $delete = false)
    {
        $cache_code = Caches::get("{$mobile}-{$event}");
        if (!$cache_code) return self::setError('验证码已过期');
        if ($code != $cache_code) return self::setError('验证码错误');
        if ($delete) Caches::delete("{$mobile}-{$event}");
        return true;
    }

    public static function clear($mobile, $event)
    {
        return Caches::delete("{$mobile}-{$event}");
    }
}